package fr.coding.kata.nantes.countwords.michel;

import fr.coding.kata.nantes.countwords.commons.KataCountWordsInterface;

import java.util.*;

public class CountWords implements KataCountWordsInterface {

    private Map<String, Integer> words = new HashMap<String, Integer>();

    private String[] SEPARATORS = {" ", "\n", "\r"};
    private String word;

    @Override
    public Integer call() throws Exception {

        Integer count = words.get(word);

        return count == null ? 0 : count;
    }

    @Override
    public KataCountWordsInterface withText(String text) {
        List<String> texts = new ArrayList<String>();
        texts.add(text);
        for (String separator : SEPARATORS) {
            texts = processListWithSeparator(texts, separator);
        }
        createMapFrom(texts);
        return this;
    }

    private void createMapFrom(List<String> texts) {
        for (String word : texts) {
            Integer count = words.get(word);
            if (null == count)
                count = 1;
            else
                ++count;
            words.put(word, count);
        }

    }

    private List<String> processListWithSeparator(List<String> texts,
                                                  String separator) {
        List<String> newList = new ArrayList<String>();
        for (String string : texts) {
            newList.addAll(Arrays.asList(string.split(separator)));
        }
        return newList;
    }

    @Override
    public KataCountWordsInterface withWord(String word) {
        this.word = normalize(word);
        return this;
    }

    private String normalize(String word) {
        return word.trim().toLowerCase();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new CountWords().withText("string")
                .withWord("string").call());
    }
}
